import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:lcapp/api/interface/message.dart';
import 'package:lcapp/api/request/response_data.dart';
import 'package:lcapp/basic/local_info.dart';
import 'package:lcapp/config/const_config.dart';
import 'package:lcapp/data/message_data_entity.dart';
import 'package:lcapp/model/event/event_bus.dart';
import 'package:lcapp/model/popover/popover.dart';
import 'package:lcapp/page/fabu_menu.dart';
import 'package:lcapp/page/faxian/faxian.dart';
import 'package:lcapp/page/home/home.dart';
import 'package:lcapp/page/home/home_new.dart';
import 'package:lcapp/page/min/minpage.dart';
import 'package:lcapp/widget/lc_gesture_detector.dart';

import '../model/mqtt/MQTTManager.dart';

int tabIndex = 0;
late TabController bottomTabController;
class IndexPage extends StatefulWidget {
  const IndexPage({Key? key,}) : super(key: key);

  @override
  _IndexPageState createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage> with SingleTickerProviderStateMixin,AutomaticKeepAliveClientMixin{

  late StreamSubscription _subscription;
  late StreamSubscription loginSub;
  late StreamSubscription msgSub;
  late MessageDataEntity messageDataEntity;
  int unRead = 0;

  late MQTTService _mqttManager = MQTTService();

  List<Widget> tabContents = [
    HomeNewPage(),
    HomePage(),
    // XianHuoPage(),
    FaxianPage(),
    MinPage()
  ];
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    bottomTabController =
        TabController(length: 4, vsync: this);
    bottomTabController.index = tabIndex;
    bottomTabController.addListener(_tabListener);
    _subscription = eventBus.on<HomeToIndex>().listen((event) {
      setState(() {
        tabIndex = event.index!;
        bottomTabController.animateTo(tabIndex);
      });
    });
    loginSub = eventBus.on<LoginState>().listen((event) {
      if(AsrLocalInfo.token!=null){
        getSystemMsg();
      }
    });

    msgSub = eventBus.on<MessageUnReadState>().listen((event) {
      if(AsrLocalInfo.token!=null){
        getSystemMsg();
      }
    });
    if(AsrLocalInfo.token!=null){
      getSystemMsg();
    }
    _initMQTT();
  }

  Future<void> _initMQTT() async {
    _mqttManager.connect().then((_) {
      _mqttManager.subscribe('/LC25000001');
      _mqttManager.publish('/LC25000001', 'Hello MQTT!');
    });
  }

  _tabListener(){
    if(bottomTabController.index==0){
      if(AsrLocalInfo.token!=null){
        PopoverManager.getPops();
      }
    }
    eventBus.fire(HomeChangeIndex(canPlay:bottomTabController.index==1));
    getSystemMsg();
  }
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _subscription.cancel();
    loginSub.cancel();
    msgSub.cancel();
    bottomTabController.removeListener(_tabListener);
  }

  getSystemMsg()async{
    ResponseData res = await MessageAPI.getLastMessage();
    if(res.code==200&&res.data!=null){
      if(mounted){
        setState(() {
          messageDataEntity = MessageDataEntity().fromJson(res.data);
          int sys = messageDataEntity.sysUnReadCount ??0;
          int hd = messageDataEntity.hdUnReadCount ?? 0;
          int fd = messageDataEntity.friendUnReadCount ??0;
          unRead = sys + hd + fd;
        });
      }
    }
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: TabBarView(
        /*禁止左右滑动*/
        physics: NeverScrollableScrollPhysics(),
        controller: bottomTabController,
        children: tabContents,
      ),
      bottomNavigationBar: Container(
        padding: EdgeInsets.only(bottom: ScreenUtil().bottomBarHeight>0?20.w:0),
        height: 120.w+(ScreenUtil().bottomBarHeight>0?20.w:0),
        decoration: BoxDecoration(
          color: tabIndex!=1 ? Colors.white:Colors.black,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.2),
              blurRadius: 20,
            ),
          ]
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            GestureDetector(
              onTap: (){
                if(tabIndex!=0){
                  tabClick(0);
                }
              },
              child: Container(
                width: 1.sw/5,
                alignment: Alignment.center,
                color: Colors.transparent,
                child: Text('首页',style: TextStyle(
                    color: tabIndex!=1?Colors.black:Colors.white,
                    fontSize: 35.sp,
                    fontWeight: tabIndex==0? FontWeight.w600:FontWeight.w400
                ),),
              ),
            ),
            GestureDetector(
              onTap: (){
                if(tabIndex!=1){
                  tabClick(1);
                }
              },
              child: Container(
                width: 1.sw/5,
                alignment: Alignment.center,
                color: Colors.transparent,
                child: Text('粮视',style: TextStyle(
                    color: tabIndex!=1?Colors.black:Colors.white,
                    fontSize: 35.sp,
                    fontWeight: tabIndex==1? FontWeight.w600:FontWeight.w400
                ),),
              ),
            ),
            lcGestureDetector(
              isLogin:true,
              onTap: (){
                eventBus.fire(HomeChangeIndex(canPlay:false));
                SmartDialog.show(
                  alignment: Alignment.bottomCenter,
                  clickMaskDismiss: false,
                  maskColor: Colors.transparent, builder: (BuildContext context) {
                    return FabuMenuPage();
                });
              },
              child: Container(
                width: 1.sw/5,
                alignment: Alignment.center,
                child: Image.asset("assets/tab/fabu.png",height: 100.w,fit: BoxFit.fitHeight,),
              ),
            ),
            lcGestureDetector(
              isLogin:true,
              onTap: (){
                if(tabIndex!=2){
                  tabClick(2);
                }
              },
              child: Container(
                width: 1.sw/5,
                alignment: Alignment.center,
                child: Stack(
                  clipBehavior: Clip.none,
                  children: [
                    Text('消息',style: TextStyle(
                        color: tabIndex!=1?Colors.black:Colors.white,
                        fontSize: 35.sp,
                        fontWeight: tabIndex==2? FontWeight.w600:FontWeight.w400
                    ),),
                    Positioned(child: Visibility(
                      child: Container(
                        width: 18,
                        height: 18,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                            color: defaultBarColor,
                            borderRadius: BorderRadius.all(Radius.circular(40))
                        ),
                        child: Text('$unRead',style: TextStyle(
                          color: Colors.white,
                          fontSize: 20.sp,
                        ),),
                      ),
                      visible: unRead != 0,
                    ),top: -9,right: -10,)
                  ],
                ),
              ),
            ),
            lcGestureDetector(
              isLogin:true,
              onTap: (){
                if(tabIndex!=3){
                  tabClick(3);
                }
              },
              child: Container(
                width: 1.sw/5,
                alignment: Alignment.center,
                color: Colors.transparent,
                child: Text('我的',style: TextStyle(
                    color: tabIndex!=1?Colors.black:Colors.white,
                    fontSize: 35.sp,
                    fontWeight: tabIndex==3? FontWeight.w600:FontWeight.w400
                ),),
              ),
            ),
          ],
        ),
      ),
    );
  }

  void tabClick(int index){
    setState(() {
      tabIndex=index;
      bottomTabController.animateTo(tabIndex,);
    });
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
